import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app_demo/common/event_bus.dart';
import 'package:flutter_app_demo/constants/constants.dart';
import 'package:flutter_app_demo/pages/login_web_page.dart';
import 'package:flutter_app_demo/utils/NetUtils.dart';
import 'package:flutter_app_demo/utils/data_utils.dart';
import 'package:flutter_app_demo/widget/news_list_widget.dart';

class NewsListPage extends StatefulWidget {
  @override
  _NewsListPageState createState() => _NewsListPageState();
}

class _NewsListPageState extends State<NewsListPage> {
  bool _isLogin = false;

  ScrollController _controller = ScrollController();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    //滚动控制器
    _controller.addListener(() {
      var maxScroll = _controller.position.maxScrollExtent;
      var pixels = _controller.position.pixels;
      //position = ScrollPositionWithSingleContext#2ff90(offset: 34.3, range: 0.0..Infinity, viewport: 642.4, ScrollableState, ClampingScrollPhysics -> RangeMaintainingScrollPhysics, BallisticScrollActivity#3d09f(AnimationController#6ea12(▶ 34.323; for BallisticScrollActivity)), ScrollDirection.forward)
      print("position = ${_controller.position}");
      print("position = ${_controller.position}");
      if (maxScroll == pixels) {
        _currentPage++;
        getNewsList(true);
      }
    });

    //网络获取数据
    DataUtils.isLoging().then((isLogin) {
      if (!mounted) {
        return;
      }

      setState(() {
        _isLogin = isLogin;
      });
      //获取新闻
      getNewsList(false);
    });

    eventBus.on<LoginEvent>().listen((event) {
      //登录
      if (!mounted) {
        return;
      }

      setState(() {
        _isLogin = true;
      });
    });

    eventBus.on<LogoutEvent>().listen((event) {
      //登出
      if (!mounted) {
        return;
      }

      setState(() {
        _isLogin = false;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    if (_isLogin == null || !_isLogin) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text("由于openapi限制，必须登录才能获取咨询"),
            InkWell(
              onTap: () async {
                final result = await Navigator.of(context)
                    .push(MaterialPageRoute(builder: (context) {
                  return LoginWebPage();
                }));

                if (result != null && result == "refresh") {
                  //发送登录成功的事件
                  eventBus.fire(LoginEvent());
                }
              },
              child: Text("去登录"),
            )
          ],
        ),
      );
    }
    return RefreshIndicator(
      child: buildListView(),
      onRefresh: _pullToRefresh,
    );
  }

  Widget buildListView() {
    if (newList == null) {
      getNewsList(false);
      return CupertinoActivityIndicator();
    }
    return ListView.builder(
        //添加滚动控制器
        controller: _controller,
        itemCount: newList.length,
        itemBuilder: (context, index) {
          return NewsListItem(data: newList[index]);
        });
  }

  int _currentPage = 1;

  List newList;

  void getNewsList(bool isLoadMore) async {
    DataUtils.isLoging().then((isLogin) {
      if (isLogin) {
        DataUtils.getAccessToken().then((token) {
          if (token == null || token.length == 0) {
            return;
          }

          //封装参数
          Map<String, dynamic> params = {
            "access_token": token,
            "catalog": 1,
            "page": _currentPage,
            "pageSize": 10,
            "dataType": "json",
          };

          NetUtils.get(AppUrls.NEWS_LIST, params).then((data) {
            //print(data);
            if (data != null && data.isNotEmpty) {
              //解析gson数据
              Map<String, dynamic> map = json.decode(data);
              print("map  = ${map.length}");
              List _newList = map["newslist"];
              print("_newList  = ${_newList.length}");
              _newList.forEach((element) {
                print("element  = $element");
              });
              setState(() {
                if (isLoadMore) {
                  newList.addAll(_newList);
                } else {
                  newList = _newList;
                }
              });
              //赋值
            }
          });
        });
      }
    });

    //I/flutter ( 1807): map  = 2
    // I/flutter ( 1807): _newList  = 10
    // I/flutter ( 1807): element  = {author: 局长, id: 147769, title: Windows 11 “利好” Linux 发行版？, type: 4, authorid: 2720166, pubDate: 2021-06-26 09:34:30, commentCount: 2}
    // I/flutter ( 1807): element  = {author: WebMIS, id: 147768, title: WebMIS v2.0.0 正式版，高性能轻量级全栈开发基础框架, type: 4, authorid: 1047905, pubDate: 2021-06-26 09:28:43, commentCount: 0}
    // I/flutter ( 1807): element  = {author: 御坂弟弟, id: 147767, title: 戴尔 SupportAssist 漏洞危及 3000 万台 PC , type: 4, authorid: 2744687, pubDate: 2021-06-26 09:05:11, commentCount: 0}
    // I/flutter ( 1807): element  = {author: 御坂弟弟, id: 147765, title: Google 计划到 2023 年逐步淘汰 Chrome 中的第三方 cookie, type: 4, authorid: 2744687, pubDate: 2021-06-26 08:21:18, commentCount: 0}
    // I/flutter ( 1807): element  = {author: SOFAStack, id: 147764, title: MOSN 子项目 Layotto：开启服务网格+应用运行时新篇章, type: 4, authorid: 4081603, pubDate: 2021-06-26 08:20:57, commentCount: 0}
    // I/flutter ( 1807): element  = {author: 白开水不加糖, id: 147763, title: Confluent IPO 融资 8.28 亿美元，上市首日股价上涨 25%, type: 4, authorid: 4252687, pubDate: 2021-06-26 08:17:22, commentCount: 0}
    // I/flutter ( 1807): element  = {author: 局长, id: 147762, title: Typesense —— 快速、可容忍错字的搜索引擎, type: 1, authorid: 2720166, pubDate: 2021-06-26 08:15:06, object: 52127, commentCount: 0}
    // I/flutter ( 1807): element  = {author: 局长, id: 147761, title: 每日一博 | 一次“不负责任”的 K8s 网络故障排查经验分享, type: 3, authorid: 2720166, pubDate: 2021-06-26 08:12:38, commentCount: 0, object: 5087054}
    // I/flutter ( 1807): element  = {author: 局长, id: 147760, title: Gitee 推荐 | C# 开发的浏览器控制工具 pyWebBrowser3, type: 0, authorid: 2720166, pubDate: 2021-06-26 08:10:32, url: https://gitee.com/Yogurt_cry/pyWebBrowser3, object: 0, commentCount: 0}
    // I/flutter ( 1807): element  = {author: 白开水不加糖, id: 147759, title: TiDB 5.1 发布，分布式 NewSQL 数据库, type: 4, authorid: 4252687, pubDate: 2021-06-26 07:36:59, commentCount: 0}

    //{
    //   "newslist": [
    //     {
    //       "author": "Alias_Travis",
    //       "id": 146738,
    //       "title": "Red Panda Dev C++ —— C/C++ 集成开发环境",
    //       "type": 1,
    //       "authorid": 4937141,
    //       "pubDate": "2021-06-20 08:03:48",
    //       "object": 51692,
    //       "commentCount": 0
    //     },
  }

  Future<void> _pullToRefresh() async {
    getNewsList(false);
  }
}
